package com.bluefish.bltuan.action.admin;

import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;

import com.bluefish.bltuan.annotation.Before;
import com.bluefish.bltuan.cache.ApplicationUtils;
import com.bluefish.bltuan.module.Category;
import com.bluefish.bltuan.service.CategoryService;

@Results({
	@Result(name = "list", type = "redirect", location = "/admin/city")
})
public class CityAction extends AdminAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 7429922144023765620L;
	
	private String name;
	
	private boolean start;
	
	private String nickname;

	private CategoryService categoryService;

	private List<Category> cities;
	
	private Category currentCity;
	
	@Before(include = {"destroy", "start", "close", "edit", "update"})
	public void prepare(){
		this.currentCity = this.categoryService.findById(getIntegerId());
	}
	
	@Override
	public HttpHeaders create() {
		Category city = new Category();
		city.setName(this.name);
		city.setStart(this.start);
		city.setNickname(this.nickname);
		this.categoryService.addCity(city);
		return new DefaultHttpHeaders(LIST).disableCaching();
	}

	@Override
	public String destroy() {
		this.categoryService.delete(this.currentCity);
		updateCacheCities();
		redirect();
		return null;
	}
	
	public String start(){
		this.categoryService.startCity(this.currentCity);
		updateCacheCities();
		redirect();
		return null;
	}
	
	public String close(){
		this.categoryService.closeCity(this.currentCity);
		updateCacheCities();
		redirect();
		return null;
	}

	@Override
	public String edit() {
		return EDIT;
	}

	@Override
	public HttpHeaders editNew() {
		return new DefaultHttpHeaders(NEW).disableCaching();
	}

	@Override
	public HttpHeaders index() {
		this.cities = this.categoryService.listCities(getPageIndex());
		return new DefaultHttpHeaders(INDEX).disableCaching();
	}

	@Override
	public HttpHeaders show() {
		return null;
	}

	@Override
	public String update() {
		this.currentCity.setName(this.name);
		this.currentCity.setStart(this.start);
		this.currentCity.setNickname(this.nickname);
		this.categoryService.update(currentCity);
		updateCacheCities();
		return LIST;
	}
	
	private void updateCacheCities(){
		ApplicationUtils.updateCities(ServletActionContext.getServletContext(),
				categoryService);
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public List<Category> getCities() {
		return cities;
	}
	
	public Category getCurrentCity() {
		return currentCity;
	}
	
	public void setStart(boolean start) {
		this.start = start;
	}
	
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
}
